package org.lhl.readruler.utils

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import io.reactivex.Flowable
import io.reactivex.disposables.Disposable
import io.reactivex.processors.PublishProcessor

/**
 * Created by luohaolun.
 * Date: 2019/5/29
 */

val process = PublishProcessor.create<Any>().toSerialized()

inline fun <reified T> rxRegister(): Flowable<T> = process.ofType(T::class.java)

fun rxPush(any: Any) = process.onNext(any)


fun Disposable.auto(key: String? = null, lifecycle: Lifecycle, map:MutableMap<String, MyLifecycleObserver>) {
    val ob = MyLifecycleObserver(this, lifecycle)
    if (key != null) {
        map.remove(key)?.clear()
        map[key] = ob
    }
    lifecycle.addObserver(ob)
}

class MyLifecycleObserver(private val dispose: Disposable, private val lifecycle: Lifecycle) : LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {
        dispose.dispose()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause() {
        if (dispose.isDisposed)
            lifecycle.removeObserver(this)
    }

    fun clear() {
        dispose.dispose()
        lifecycle.removeObserver(this)
    }
}